﻿using System;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DigitalSum.Web.UI.WebControls
{
    public enum DataSourceBehavior
    {
        Default = 0,
        PageRelated = 1,
        TemplateRelated = 2
    }

    public class ObjectDataSource : System.Web.UI.WebControls.ObjectDataSource
    {
        #region PROPERTIES

        public string KeysBuilderSeparator { get { return "\\"; } }
        private HiddenField _hdfStateKey;
        //private string _stateKey;
        private string StateKey
        {
            get
            {
                if (string.IsNullOrEmpty(_hdfStateKey.Value)) return null;
                return _hdfStateKey.Value;
            }
        }

        private DataSourceBehavior _behavior;
        public DataSourceBehavior Behavior
        {
            get
            {
                return _behavior;
            }
            set
            {
                _behavior = value;
            }
        }

        public override string CacheKeyDependency
        {
            get
            {
                if (_manager.Launched)
                {
                    if (string.IsNullOrEmpty(base.CacheKeyDependency))
                        base.CacheKeyDependency = this.StateKey;
                }
                return base.CacheKeyDependency;
            }
            set
            {
                if (_manager.Launched)
                {
                    _hdfStateKey.Value = value;
                }
                base.CacheKeyDependency = _hdfStateKey.Value;
            }
        }
        #endregion

        #region CONSTRUCTORS

        public ObjectDataSource() : base() { _Init(); }

        public ObjectDataSource(string typeName, string selectMethod) : base() { _Init(); }

        #region INITIALIZATIONS
        ContextManager _manager;
        private void _Init()
        {
            _manager = new ContextManager();
        }
        #endregion

        #endregion

        #region METHODS

        protected override void OnInit(EventArgs e)
        {
            if (_manager.Launched)
            {
                //this.Init += new EventHandler(ObjectDataSource_Init);

                if (_hdfStateKey == null)
                {
                    _hdfStateKey = new HiddenField();
                    _hdfStateKey.ID = "SK";
                }

                if (this.Behavior == DataSourceBehavior.TemplateRelated)
                {
                    this.EnableCaching = true;
                    this.CacheDuration = 300; // 5 min
                    this.CacheExpirationPolicy = DataSourceCacheExpiry.Sliding;
                }
            }

            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (_manager.Launched)
            {
                if (this.Parent == null || this.Parent.Visible)
                {
                    if (this.Behavior == DataSourceBehavior.TemplateRelated)
                    {
                        if (Page.Request.Form[this.UniqueID + '_' + _hdfStateKey.ID] != null)
                        {
                            _hdfStateKey.Value = Page.Request.Form[this.UniqueID + '_' + _hdfStateKey.ID];
                            this.CacheKeyDependency = StateKey ?? "";//
                        }
                        else
                        {
                            //if (string.IsNullOrEmpty(this.CacheKeyDependency))//!Page.IsPostBack && !Page.IsCallback)
                            {
                                DateTime now = DateTime.Now;
                                //_stateKey = string.Format("{0}${1:yyyyMMddhhmmss}{2:d3}", /*((Control)this).AppRelativeTemplateSourceDirectory*/ Page.Request.Path, DateTime.Now, DateTime.Now.Millisecond);
                                //_stateKey = string.Format("{1}{0}{2}{0}{3}{0}{4:yyyyMMddhhmmss}{5:d3}", KeysBuilderSeparator, this.Page.Request.Path, this.UniqueID, this.Context.Session.SessionID, now, now.Millisecond);
                                //string stateKey = string.Format("{1}{0}{2}{0}{3}{0}{4:yyyyMMddhhmmss}{5:d3}", KeysBuilderSeparator, this.AppRelativeTemplateSourceDirectory, this.UniqueID, this.Context.Session.SessionID, now, now.Millisecond);
                                //string stateKey = string.Format("{1}{0}{2}", KeysBuilderSeparator, this.TemplateControl.GetType().FullName, this.UniqueID);
                                string stateKey = string.Format("{1}", KeysBuilderSeparator, this.TypeName.ToLowerInvariant());// .GetType().FullName, this.UniqueID);

                                _hdfStateKey.Value = stateKey;
                                //this.ViewState["PageRelatedKey"] = _stateKey;
                                this.CacheKeyDependency = StateKey ?? "";//

                                if (this.Context.Cache[this.CacheKeyDependency] != null)
                                    this.Context.Cache.Remove(this.CacheKeyDependency);
                                this.Context.Cache[this.CacheKeyDependency] = DateTime.Now;
                            }
                        }
                        //if (this.UniqueID.Contains(this.Parent.ID))
                        {
                        }
                        // }
                        //this.Selecting += new ObjectDataSourceSelectingEventHandler(_Selecting);
                        this.Selected += new ObjectDataSourceStatusEventHandler(ObjectDataSource_Selected);
                        this.Updated += new ObjectDataSourceStatusEventHandler(ObjectDataSource_Updated);
                    }
                    else
                    {
                    }
                }
                else
                {
                }
            }
        }

        public override void RenderControl(System.Web.UI.HtmlTextWriter writer)
        {
            //if (_hdfStateKey != null)
            //    this.Controls.Add(_hdfStateKey);
            base.RenderControl(writer);

            if (_manager.Launched)
            {
                if (this.Behavior == DataSourceBehavior.TemplateRelated)
                {
                    if (_hdfStateKey == null)
                    {
                        //_hdfStateKey = new HiddenField();
                        //// _hdfStateKey.ID = SelectFieldName + "_filter";
                        //_hdfStateKey.Value = null;
                    }
                    if (_hdfStateKey.Value == null)
                    {                      
                        //_hdfStateKey.Value = ;
                    }

                    if (this.UniqueID.Contains(this.Parent.ID))
                    {
                        _hdfStateKey.ID = this.UniqueID + '_' + _hdfStateKey.ID;
                        _hdfStateKey.RenderControl(writer);
                    }
                }
            }
        }

        protected void ObjectDataSource_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
            //if (!string.IsNullOrEmpty(this.CacheKeyDependency))
            //{
            //    //  this.Context.Cache[this.CacheKeyDependency] = DateTime.Now;
            //}
            ////e.InputParameters["champs"] = _od;//Session["gdDemandes_myFields"];
        }

        protected void ObjectDataSource_Updated(object sender, ObjectDataSourceStatusEventArgs e)
        {
            if (!string.IsNullOrEmpty(this.CacheKeyDependency))
            {
                this.Context.Cache.Remove(this.CacheKeyDependency);
                this.Context.Cache[this.CacheKeyDependency] = DateTime.Now;
            }
        }

        #endregion
    }
}